import { createRouter, createWebHistory } from 'vue-router'
import UserList from '../views/UserList.vue'
import UserDetail from '../views/UserDetail.vue'

// 基础路径：独立运行时为根路径，被qiankun加载时为/user
const baseUrl = window.__POWERED_BY_QIANKUN__ ? '/user' : '/'

const routes = [
  {
    path: '/',
    name: 'UserList',
    component: UserList,
    meta: {
      title: '用户列表'
    }
  },
  {
    path: '/detail/:id',
    name: 'UserDetail',
    component: UserDetail,
    meta: {
      title: '用户详情'
    }
  }
]

const router = createRouter({
  history: createWebHistory(baseUrl),
  routes,
  // 路由切换时滚动到顶部
  scrollBehavior() {
    return { top: 0 }
  }
})

// 路由守卫：更新页面标题
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title + ' - 用户管理'
  }
  next()
})

export default router
